package ma.moliere.transverse.utils;


import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.beanutils.NestedNullException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.comparators.NullComparator;
import org.richfaces.log.LogFactory;
import org.richfaces.log.Logger;



public class NullSafeBeanComparator extends BeanComparator {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4252499214766094605L;
	private static Logger LOGGER = LogFactory.getLogger();

	public NullSafeBeanComparator(final String property) {
		super(property, new NullComparator());
	}
	
	@SuppressWarnings("unchecked")
	public final int compare(final Object o1, final Object o2) {
		int retour = 0;
		if (getProperty() == null) {
			// compare the actual objects
			retour = getComparator().compare(o1, o2);
		}

		try {
			Object value1 = null;
			Object value2 = null;
			try {
				value1 = PropertyUtils.getProperty(o1, getProperty());
			} catch (NestedNullException e) {
				LOGGER.debug(e.getMessage());
			}

			try {
				value2 = PropertyUtils.getProperty(o2, getProperty());
			} catch (NestedNullException e) {
				LOGGER.debug(e.getMessage());
			}

			retour = getComparator().compare(value1, value2);
		} catch (Exception e) {
			LOGGER.debug(e.getMessage());
		}
		return retour;
	}
}
